package function

import (
	"SalesMangent/models"

	"github.com/gin-gonic/gin"
)

func GetAllClient(clientParam map[string]interface{}) (error, []models.Sclient, int64) {
	var clientData []models.Sclient
	page := clientParam["page"].(int)
	pageSize := clientParam["limit"].(int)
	searchName := clientParam["searchName"].(string)
	var total int64
	err := db.Table("s_client s").Select("s.c_code, s.c_code_name, s.c_name, s.c_phone, s.c_post").Where("s.c_code_name like ?", searchName+"%").Order("c_code ASC").Count(&total).Offset((page + 1) * pageSize).Limit(pageSize).Find(&clientData).Error
	return err, clientData, total
}

func DelClient(code string) error {
	err := db.Table("s_client").Where("c_code = ?", code).Delete(models.Sclient{}).Error
	return err
}

func AddClient(a *gin.Context) (error, models.Sclient) {
	var clientData models.Sclient
	clientData.Ccode = a.PostForm("c_code")
	clientData.Ccodename = a.PostForm("c_code_name")
	clientData.Cname = a.PostForm("c_name")
	clientData.Cphone = a.PostForm("c_phone")
	clientData.Cpost = a.PostForm("c_post")
	err := db.Table("s_client").Select("c_code", "c_code_name", "c_name", "c_phone", "c_post").Create(&clientData).Error
	return err, clientData
}

func UpdateClient(a *gin.Context) error {
	var clientData models.Sclient
	clientData.Ccode = a.PostForm("c_code")
	clientData.Ccodename = a.PostForm("c_code_name")
	clientData.Cname = a.PostForm("c_name")
	clientData.Cphone = a.PostForm("c_phone")
	clientData.Cpost = a.PostForm("c_post")
	err := db.Table("s_client").Where("c_code = ?", clientData.Ccode).Updates(&clientData).Error
	return err
}

